package com.example.administrator.tenyuanpackage.speacial.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewTreeObserver;

import com.example.administrator.tenyuanpackage.R;
import com.example.administrator.tenyuanpackage.speacial.activity.TeMai2Activity;
import com.example.administrator.tenyuanpackage.speacial.adapter.TeMaiRecyclerViewAdapter;
import com.example.administrator.tenyuanpackage.speacial.bean.TeMaiBean;
import com.example.administrator.tenyuanpackage.speacial.util.IApi;
import com.example.administrator.tenyuanpackage.speacial.util.NetUtils;
import com.example.administrator.tenyuanpackage.speacial.util.URLConfigs;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yq on 2017/2/27.
 */

public class TeMaiFragment extends LazyFragment {

    private IApi mIApi = NetUtils.getInstance().getApi();
    private RecyclerView recyclerView;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private TeMaiRecyclerViewAdapter adapter;
    private int page = 1;
    private ArrayList<TeMaiBean.RowsBean> list = new ArrayList<>();

    public static Fragment getInsatance(int i) {
        TeMaiFragment fragment = new TeMaiFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", i);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void init(View view) {

        final int typeIndex = getArguments().getInt("type");
        final int shang[] = {99, 98, 97, 1, 5};

        recyclerView = (RecyclerView) view.findViewById(R.id.teMai_RecyclerView);
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.temai_swipeRefreshLayout);

        //布局管理器
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);

        adapter = new TeMaiRecyclerViewAdapter(getContext(), list);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new TeMaiRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Intent intent=new Intent(getActivity(), TeMai2Activity.class);
                startActivity(intent);
            }
        });


        //下拉刷新
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //网络请求
                toJson(URLConfigs.zuiXin_baseURL + shang[typeIndex] + URLConfigs.zuiXin_houURL);
            }
        });

        //通过观察者自动加载
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mSwipeRefreshLayout.setRefreshing(true);
                toJson(URLConfigs.zuiXin_baseURL + shang[typeIndex] + URLConfigs.zuiXin_houURL);
                //取消观察者
                root.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

        //上拉加载

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem;

            //滑动到底部
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        lastVisibleItem + 1 == adapter.getItemCount()) {
                    if (!mSwipeRefreshLayout.isRefreshing()) {
                        mSwipeRefreshLayout.setRefreshing(true);
                        toJson(URLConfigs.fenYe_baseURL + (++page) + URLConfigs.fenYe_zhongJianURL + shang[typeIndex] + URLConfigs.zuiXin_houURL);

                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                RecyclerView.LayoutManager layoutManget = recyclerView.getLayoutManager();
                if (layoutManget instanceof LinearLayoutManager) {
                    int last = ((LinearLayoutManager) layoutManget).findLastVisibleItemPosition();
                    if (last != -1) {
                        lastVisibleItem = last;
                    }
                }
            }
        });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_te_mai;
    }

    //网络
    public void toJson(String url) {
        Call<String> call = mIApi.getData(url);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                mSwipeRefreshLayout.setRefreshing(false);
                String json = response.body();


                for (int i = 0; i < parseJsonToGoodsBean(json).getRows().size(); i++) {
                    list.add(parseJsonToGoodsBean(json).getRows().get(i));
                }
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });


    }

    public TeMaiBean parseJsonToGoodsBean(String jsonString) {
        Gson gson = new Gson();
        return gson.fromJson(jsonString, new TypeToken<TeMaiBean>() {}.getType());
    }
}
